from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
from rest_framework import serializers
import random
from utils.ytx_sdk.sendSMS import CCP
from celery_tasks.sms.tasks import sms_send


class SMSCodeView(APIView):
    def get(self, request, mobile):
        '''
        接收手机号
        :param request:
        :param mobile:
        :return:
        检查是否在60s内有发送记录
        生成短信验证码
        保存短信验证码与发送记录
        发送短信
        '''
        # 连接数据库redis
        redis_cli = get_redis_connection('verify_code')
        sms_flag = redis_cli.get('sms_flag' + mobile)
        if sms_flag:
            raise serializers.ValidationError('请稍后再发送短信验证码！')
        # 生成短信验证码
        sms_code = str(random.randint(100000, 999999))
        # 保存短信验证码与发送记录
        # redis_cli.setex('sms_code' + mobile, 300, sms_code)
        # redis_cli.setex('sms_flag' + mobile, 60, 1)
        # 优化redis的交互，减少交互次数，管道pipeline
        redis_pl = redis_cli.pipeline()
        redis_pl.setex('sms_code' + mobile, 300, sms_code)
        redis_pl .setex('sms_flag' + mobile, 60, 1)
        redis_pl.execute()
        # 发送短信，使用第三方包云通讯
        # CCP.sendTemplateSMS(mobile, sms_code, 5, 1)
        sms_send.delay(mobile, sms_code, 5, 1)

        print(sms_code)
        return Response({'massage': 'ok!'})
